<?php
/**
 * 产品分表
 * 分表规则：表名+公司id+语言名称
 * Created by PhpStorm.
 * User: pc
 * Date: 2018/12/14
 * Time: 17:07
 */

namespace app\admin\model;

use think\Db;
use think\Model;
use app\Config;
use PDO;

class Product extends Model
{
    public $pdo = '';
    public $dbName = '';

    public function __construct()
    {
        $dbms = $this->getConfig('type');     //数据库类型
        $host = $this->getConfig('hostname'); //数据库主机名
        $this->dbName = $this->getConfig('database');    //使用的数据库
        $this->pdo = new PDO("$dbms:host=$host;dbname=$this->dbName", $this->getConfig('username'), $this->getConfig('password'));
    }

    /**
     * 检测数据表是否存在
     * @param string $table
     * @return bool
     */
    public function checkTableExist($table = '')
    {
        $tableName = $table ? $table : self::getTable();
        $sql = sprintf("SELECT COUNT(1) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`='%s' AND `TABLE_NAME` = '%s'", $this->dbName, $this->getConfig('prefix') . $tableName);
        $result = $this->pdo->query($sql);
        if ($result === false) {//表不存在
            return false;
        }
        if (!$result->fetchColumn(0)) {
            return false;
        }
        return true;
    }

    /**
     * 复制表结构
     * @param string $table
     * @param string $newTable
     * @param string $company_id
     * @return bool
     */
    public function copyTable($table = '', $newTable = '')
    {
        $table = $this->getConfig('prefix') . $table;
        $newTable = $this->getConfig('prefix') . $newTable;
        $sql = sprintf("create table %s like %s", $newTable, $table);
        $result = $this->pdo->query($sql);
        if ($result === false) {
            return false;
        }
        $sql = sprintf("alter table %s comment '%s'", $newTable, $table . '_分表');
        $this->pdo->query($sql);
        return true;
    }

    /**
     * 用户绑定产品分表
     * @return mixed|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getProductTbale()
    {
        $productTbale = 'products';
        $resourceTbale = "resource";

        $list = DB::name('product_table')->order('id desc')->limit(1)->find();
        //不存在分表，创建第一张分表
        if (!checkArr($list)) {
            $newProductTbale = $productTbale . '_1';
            $newresourceTbale = $resourceTbale . '_1';
            $this->copyTable($productTbale, $newProductTbale);
            $this->copyTable($resourceTbale, $newresourceTbale);
            DB::name('product_table')->insert(['product' => $newProductTbale, 'source' => $newresourceTbale, 'status' => 1], 'IGNORE');
            return 1;
        }

        $num = DB::name($list['product'])->count();
        //最新分表数量小于10000，直接返回绑定
        if ($num < 10000) {
            return $list['id'];
        }
        //最新分表数据超过10000，创建新的分表，返回绑定
        $id = $list['id'] + 1;
        $newProductTbale = $productTbale . '_' . $id;
        $newresourceTbale = $resourceTbale . '_' . $id;
        $this->copyTable($productTbale, $newProductTbale);
        $this->copyTable($resourceTbale, $newresourceTbale);
        DB::name('product_table')->insert(['product' => $newProductTbale, 'source' => $newresourceTbale, 'status' => 1], 'IGNORE');
        DB::name('product_table')->where('id', $list['id'])->update(['status' => 2]);
        return $id;
    }
}